package org.linlinjava.litemall.wx.web;

import com.alibaba.fastjson.JSONObject;
import com.xxl.sso.core.conf.Conf;
import com.xxl.sso.core.login.SsoWebLoginHelper;
import com.xxl.sso.core.user.XxlSsoUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.notify.NotifyService;
import org.linlinjava.litemall.core.util.*;
import org.linlinjava.litemall.db.domain.LitemallCustomer;
import org.linlinjava.litemall.db.domain.LitemallCustomerLicense;
import org.linlinjava.litemall.db.service.LitemallCustomerLicenseService;
import org.linlinjava.litemall.db.service.LitemallCustomerService;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.linlinjava.litemall.db.service.TUserService;
import org.linlinjava.litemall.db.util.BadWordUtil;
import org.linlinjava.litemall.db.util.ImageUtil;
import org.linlinjava.litemall.wx.annotation.LoginUser;
import org.linlinjava.litemall.wx.service.CaptchaCodeManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.linlinjava.litemall.core.util.BizLicenseOCR.getLicenseInfo;
import static org.linlinjava.litemall.wx.util.WxResponseCode.AUTH_CAPTCHA_FREQUENCY;

/**
 * 鉴权服务
 */
@RestController
@RequestMapping("/wx/auth")
@Validated
public class WxAuthController {
    private final Log logger = LogFactory.getLog(WxAuthController.class);

    @Autowired
    private LitemallUserService userService;

    @Autowired
    private NotifyService notifyService;

    @Autowired
    private LitemallCustomerService customerService;

    @Autowired
    private TUserService tUserService;

    @Autowired
    private LitemallCustomerLicenseService licenseService;

    /**
     * 请求注册验证码
     *
     * @param body 手机号码 { mobile }
     * @return
     */
    @PostMapping("regCaptcha")
    public Object registerCaptcha(@RequestBody String body, HttpServletRequest request) {
        String phoneNumber = JacksonUtil.parseString(body, "phone");
        if (StringUtils.isEmpty(phoneNumber)) {
            return ResponseUtil.badArgument();
        }
        List<LitemallCustomer> customerList = customerService.queryPhone(phoneNumber);
        if (!RegexUtil.isMobileExact(phoneNumber) || customerList.size() > 0) {
            return ResponseUtil.fail(403, "该手机号已经被注册");
        }
        String ipAddr = IpUtil.getIpAddr(request);
        boolean success = CaptchaCodeManager.addIpAddress(ipAddr);
        if (!success) {
            return ResponseUtil.fail(AUTH_CAPTCHA_FREQUENCY, "您申请验证码过于频繁，不能发送");
        }
        String code = CharUtil.getRandomNum(6);
        boolean legalPhone = CaptchaCodeManager.addToCache(phoneNumber, code);
        if (!legalPhone) {
            return ResponseUtil.fail(AUTH_CAPTCHA_FREQUENCY, "该手机验证码刚刚发送，请耐心等待");
        }
        notifyService.notifySmsVerifyCode(phoneNumber, code);
        return ResponseUtil.ok();
    }

    /**
     * 请求更新验证码
     *
     *
     * @param
     * @return
     */
    @PostMapping("upCaptcha")
    public Object updateCaptcha(HttpServletRequest request) {
        XxlSsoUser user = (XxlSsoUser) request.getAttribute(Conf.SSO_USER);
        Long id = Long.parseLong(user.getUserid());
        String phoneNumber = customerService.getUser(id).getPhone();

        String ipAddr = IpUtil.getIpAddr(request);
        boolean success = CaptchaCodeManager.addIpAddress(ipAddr);
        if (!success) {
            return ResponseUtil.fail(AUTH_CAPTCHA_FREQUENCY, "验证码未超时1分钟，不能发送");
        }
        String code = CharUtil.getRandomNum(6);
        boolean legalPhone = CaptchaCodeManager.addToCache(phoneNumber, code);
        if (!legalPhone) {
            return ResponseUtil.fail(AUTH_CAPTCHA_FREQUENCY, "该手机验证码刚刚发送，请耐心等待");
        }
        notifyService.notifySmsVerifyCode(phoneNumber, code);
        return ResponseUtil.ok();
    }

    @PostMapping("upCaptchaCheck")
    public Object upCaptchaCheck(@RequestBody String body, HttpServletRequest request) {
        XxlSsoUser user = (XxlSsoUser) request.getAttribute(Conf.SSO_USER);
        Long id = Long.parseLong(user.getUserid());
        String phone = customerService.getUser(id).getPhone();
        String captcha = JacksonUtil.parseString(body, "captcha");
        if (!upCaptchaCheck(id, captcha)) {
            return ResponseUtil.badArgument();
        }
        String randomCode = CharUtil.getRandomString(20);
        CaptchaCodeManager.addToCacheForce(phone, randomCode);
        return ResponseUtil.ok(randomCode);
    }

    private boolean upCaptchaCheck(Long id, String captcha) {
        LitemallCustomer user = customerService.getUser(id);
        if(user == null) {
            return false;
        }
        String phone = user.getPhone();
        String realCode = CaptchaCodeManager.getCachedCaptcha(phone);
        if (StringUtils.isEmpty(captcha) || !captcha.equals(realCode)) {
            return false;
        }
        String randomCode = CharUtil.getRandomString(20);
        CaptchaCodeManager.addToCacheForce(phone, randomCode);
        return true;
    }

    /** 
     * @description 账号注册
     * @author BestN 
     * @Date 2019/11/11 
     */
    @PostMapping("register")
    public Object register(@RequestBody String body) {
        String nickName = JacksonUtil.parseString(body, "nickName");//不是必须
        if(!StringUtils.isEmpty(nickName)){
            if(nickName.length()>10){  return ResponseUtil.fail(402, "昵称不能超过10位");}
        }
        String userName = JacksonUtil.parseString(body, "userName");
        String gender = JacksonUtil.parseString(body, "gender");
        String phone = JacksonUtil.parseString(body, "phone");
        String mail = JacksonUtil.parseString(body, "mail");
        String userPassword = JacksonUtil.parseString(body, "userPassword");
        String avatar = JacksonUtil.parseString(body, "avatar");
        String invitation = JacksonUtil.parseString(body, "invitation");
        String captcha = JacksonUtil.parseString(body, "captcha");
        if (!RegexUtil.isPassword(userPassword)) {
            return ResponseUtil.fail(402, "密码必须包含:1大写/2小写/3数字/4特殊符号 中3项");
        }
        if (!RegexUtil.isMobileExact(phone)) {
            return ResponseUtil.fail(402, "手机号格式不正确");
        }
        String trueCode = CaptchaCodeManager.getCachedCaptcha(phone);
        if (StringUtils.isEmpty(captcha) || !captcha.equals(trueCode)) {
            return ResponseUtil.fail(402, "验证码填写不正确");
        }
        else {
            CaptchaCodeManager.setNullCode(phone);
        }
        String accountId = new SimpleDateFormat("yyHHddmmMMSSS").format(new Date()) + (int)(Math.random()*(9999-1000+1)+1000);
        if (StringUtils.isEmpty(nickName)) {
            nickName = "user" + accountId;
        }
        else {
            if(BadWordUtil.isContaintBadWord(nickName, BadWordUtil.maxMatchType)) {
                return ResponseUtil.fail(403, "您的昵称中有不和谐词汇");
            }
        }
        if (StringUtils.isEmpty(avatar)) {
            avatar = "http://pic.qqkuyou.com/tximg/acuwahqx.jpeg";
        }
        if (StringUtils.isEmpty(mail)) {
            mail = null;
        }
        else {
            if (!RegexUtil.isEmail(mail)) {
                return ResponseUtil.fail(402, "邮箱格式不正确");
            }
        }
        userPassword = MD5Util.md5(userPassword, "frost_forest");
        try {

            LitemallCustomer customer = new LitemallCustomer(accountId, nickName, userName, gender, phone, mail
                    , userPassword, avatar, invitation);
            tUserService.insert(customer);
            customerService.insert(customer);
            return ResponseUtil.ok();
        } catch (DuplicateKeyException e) {

            String errMsg = "重复";
            if (e.toString().contains("mail_uindex")) {
                errMsg = "邮箱 " + errMsg;
            }
            if (e.toString().contains("phone_uindex")) {
                errMsg = "手机 " + errMsg;
            }
            return ResponseUtil.fail(401,errMsg);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.fail(500, e.toString());
        }
    }
 /*
  @PostMapping("update")
   public Object update(@RequestBody String body, HttpServletRequest request) {
        XxlSsoUser user = (XxlSsoUser)  request.getAttribute(Conf.SSO_USER);
        Long id = Long.parseLong(user.getUserid());
        String nickName = JacksonUtil.parseString(body, "nickName");
        if(!StringUtils.isEmpty(nickName) && nickName.length() > 10){
          return ResponseUtil.fail(402, "昵称不能超过10位");
        }
        String userName = JacksonUtil.parseString(body, "userName");
        String gender = JacksonUtil.parseString(body, "gender");
        String phone = JacksonUtil.parseString(body, "phone");
        String mail = JacksonUtil.parseString(body, "mail");
        String userPassword = JacksonUtil.parseString(body, "userPassword");
        String avatar = JacksonUtil.parseString(body, "avatar");
        String oldPhone = customerService.getUser(id).getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            String checkCode = JacksonUtil.parseString(body, "checkCode");
            String captcha = JacksonUtil.parseString(body, "captcha");
            if (StringUtils.isAnyEmpty(checkCode, captcha)) {
                return ResponseUtil.fail(402, "您填写的验证码不正确");
            }
            String trueCode = CaptchaCodeManager.getCachedCaptcha(oldPhone);
            String trueCaptcha = CaptchaCodeManager.getCachedCaptcha(phone);
            if (!checkCode.equals(trueCode) || !captcha.equals(trueCaptcha)) {
                return ResponseUtil.fail(402, "您填写的验证码不正确");
            }
            CaptchaCodeManager.setNullCode(phone, oldPhone);
        }
        if (StringUtils.isNotEmpty(mail) && !RegexUtil.isEmail(mail) || StringUtils.isEmpty(mail) ) {
            return ResponseUtil.fail(402, "您填写的邮箱不正确");
        }
        if (StringUtils.isNotEmpty(nickName)) {
            if(BadWordUtil.isContaintBadWord(nickName, BadWordUtil.maxMatchType)) {
                return ResponseUtil.fail(403, "您的昵称中有不和谐词汇");
            }
        }
        if (StringUtils.isEmpty(mail)) {
            mail = null;
        }
        if (StringUtils.isNotEmpty(userPassword)) {
            if (!RegexUtil.isPassword(userPassword)) {
                return ResponseUtil.fail(402, "您填写的密码过于简单");
            }
            String oldPassword = JacksonUtil.parseString(body, "oldPassword");
            if (StringUtils.isEmpty(oldPassword)) {
                String captcha = JacksonUtil.parseString(body, "captcha");
                if (StringUtils.isEmpty(captcha)) {
                    return ResponseUtil.fail(402, "请输入校验");
                }
                if (upCaptchaCheck(id, captcha)) {
                    userPassword = MD5Util.md5(userPassword, "frost_forest");
                }
                else {
                    return ResponseUtil.fail(402, "您填写的旧密码不正确");
                }
            }
            else {
                oldPassword = MD5Util.md5(oldPassword, "frost_forest");
                LitemallCustomer customer = customerService.getUser(id, oldPassword);
                if (customer == null) {
                    return ResponseUtil.fail(402, "您填写的旧密码不正确");
                }
                userPassword = MD5Util.md5(userPassword, "frost_forest");
            }
        }
        try {
            LitemallCustomer newCustomer = new LitemallCustomer(nickName, userName, gender, phone, mail, userPassword, avatar);
            newCustomer.setId(id);
            customerService.update(newCustomer);
            return ResponseUtil.ok();
        } catch (DuplicateKeyException e) {
            String errMsg = "重复";
            if (e.toString().contains("mail_uindex")) {
                errMsg = "邮箱" + errMsg;
            }
            if (e.toString().contains("phone_uindex")) {
                errMsg = "手机" + errMsg;
            }
            return ResponseUtil.fail(401,errMsg);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.fail(500, "数据格式不正确");
        }
    }*/

    @PostMapping("detail")
    public Object detail(@RequestBody(required = false) String body, HttpServletRequest request) {
        Long id = null;
        if (body != null) {
            id = JacksonUtil.parseLong(body, "id");
        }
        if (id == null) {
            XxlSsoUser user = (XxlSsoUser)  request.getAttribute(Conf.SSO_USER);
            id = Long.parseLong(user.getUserid());
        }
        if (id < 1) {
            return ResponseUtil.badArgumentValue();
        }
        LitemallCustomer customer = customerService.getUser(id);
        String phone = customer.getPhone();
        phone = phone.substring(0,3) + "******" + phone.substring(9);
        customer.setPhone(phone);
        customer.setUserPassword(null);
        return ResponseUtil.ok(customer);
    }

    @PostMapping("licenseDetail")
    public Object licenseDetail(HttpServletRequest request) {
        XxlSsoUser user = (XxlSsoUser) request.getAttribute(Conf.SSO_USER);
        long id = Long.parseLong(user.getUserid());
        LitemallCustomerLicense licenseInfo = licenseService.getByUserId(id);
        if (licenseInfo==null) {
            return ResponseUtil.badArgument();
        }
        return ResponseUtil.ok(licenseInfo);
    }

    @PostMapping("invitation")
    public Object invitation(@RequestBody String msg) {
        String invitation = JacksonUtil.parseString(msg, "invitation");
        if (StringUtils.isEmpty(invitation)) {
            return ResponseUtil.badArgument();
        }
        LitemallCustomer customer = customerService.getUser(invitation);
        if (customer == null) {
            return ResponseUtil.fail(402, "未找到");
        }
        return ResponseUtil.ok(customer.getNickname());
    }

    @PostMapping("delete")
    public Object delete(@RequestBody String msg, HttpServletRequest request) {
        String password = JacksonUtil.parseString(msg, "password");
        String captcha = JacksonUtil.parseString(msg, "captcha");
        XxlSsoUser user = (XxlSsoUser) request.getAttribute(Conf.SSO_USER);
        Long id = Long.parseLong(user.getUserid());
        if (StringUtils.isEmpty(captcha)) {
            if (StringUtils.isEmpty(password)) {
                return ResponseUtil.badArgument();
            }
            LitemallCustomer customer = customerService.getUser(id, password);
            if (customer == null) {
                return ResponseUtil.fail(403, "密码不正确");
            }
        }
        else {
            if (!upCaptchaCheck(id, captcha)) {
                return ResponseUtil.fail(403, "验证码不正确");
            }
        }
        LitemallCustomer customer = customerService.getUser(id);
        customer.setIsDeleted(true);
        customer.setNickname(null);
        customer.setGender(null);
        customer.setPhone(null);
        customer.setMail(null);
        customer.setUserPassword(null);
        customerService.updateNull(customer);
        return ResponseUtil.ok();
    }

    /**
     * 账号信息更新
     *
     * @param body    请求内容
     *                {
     *                password: xxx,
     *                mobile: xxx
     *                code: xxx
     *                }
     *                其中code是手机验证码，目前还不支持手机短信验证码
     * @param request 请求对象
     * @return 登录结果
     * 成功则 { errno: 0, errmsg: '成功' }
     * 失败则 { errno: XXX, errmsg: XXX }
     */
    @PostMapping("profile")
    public Object profile(@LoginUser Integer userId, @RequestBody String body, HttpServletRequest request) {
        if(userId == null){
            return ResponseUtil.unlogin();
        }
        String avatar = JacksonUtil.parseString(body, "avatar");
        String gender = JacksonUtil.parseString(body, "gender");
        String nickname = JacksonUtil.parseString(body, "nickname");

        LitemallCustomer user = userService.findById(userId);
        if(!StringUtils.isEmpty(avatar)){
            user.setAvatar(avatar);
        }
        if(gender != null){
            user.setGender(gender);
        }
        if(!StringUtils.isEmpty(nickname)){
            user.setNickname(nickname);
        }

        if (userService.updateById(user) == 0) {
            return ResponseUtil.updatedDataFailed();
        }

        return ResponseUtil.ok();
    }

    /**
     * 微信手机号码绑定
     *
     * @param userId
     * @param body
     * @return
     */
    @PostMapping("bindPhone")
    public Object bindPhone(@LoginUser Integer userId, @RequestBody String body) {
    	if (userId == null) {
            return ResponseUtil.unlogin();
        }
        LitemallCustomer user = userService.findById(userId);
        String encryptedData = JacksonUtil.parseString(body, "encryptedData");
        String iv = JacksonUtil.parseString(body, "iv");
//        WxMaPhoneNumberInfo phoneNumberInfo = this.wxService.getUserService().getPhoneNoInfo(user.getSessionKey(), encryptedData, iv);
//        String phone = phoneNumberInfo.getPhoneNumber();
//        user.setPhone(phone);
        if (userService.updateById(user) == 0) {
            return ResponseUtil.updatedDataFailed();
        }
        return ResponseUtil.ok();
    }

    @PostMapping("logout")
    public Object logout(@LoginUser Integer userId) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        return ResponseUtil.ok();
    }

    @GetMapping("info")
    public Object info(@LoginUser Integer userId) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }

        LitemallCustomer user = userService.findById(userId);
        Map<Object, Object> data = new HashMap<Object, Object>();
        data.put("nickName", user.getNickname());
        data.put("avatar", user.getAvatar());
        data.put("gender", user.getGender());
//        data.put("mobile", user.getMobile());

        return ResponseUtil.ok(data);
    }

    @GetMapping("imQuery")
    public Object imQuery(HttpServletRequest request){
        XxlSsoUser user = (XxlSsoUser) (request.getAttribute(Conf.SSO_USER));
        String imId = user.getPlugininfo().get("imId");
        return ResponseUtil.ok(imId);
    }

    @PostMapping("loginCheck")
    public Object loginCheck(ServletRequest request, ServletResponse response) {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        // valid login user, cookie + redirect
        XxlSsoUser xxlUser = SsoWebLoginHelper.loginCheck(req, res, 0);


        // valid login fail
        if (xxlUser == null) {
           return ResponseUtil.ok(false);

        }
        return ResponseUtil.ok(true);
    }


    private static final String  PICTURE_PNG = "PNG";
    private static final String  PICTURE_JPG = "JPG";
    private static final String  PICTURE_JPEG = "JPEG";
    /**
     *  商城个人中心:普通用户:认证(上传 证书):变为商户.用户表customer中的user_type变为2.用 腾讯ORC文字识别技术(加盖公章可识别)  .core.util的BizLicenseOCR
     * @param file
     * @param request
     * @return
     */
    @PostMapping("upLicense")
    public Object upLicense(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) {
        XxlSsoUser user = (XxlSsoUser) request.getAttribute(Conf.SSO_USER);
        long id = Long.parseLong(user.getUserid());
        String randomName = CharUtil.getRandomNum(8);
        String originalFilename = file.getOriginalFilename();
        String type = originalFilename.contains(".") ? originalFilename.substring(originalFilename.lastIndexOf(".") + 1) : null;
        if (type ==null) {
            return ResponseUtil.badArgument();
        }
        if ( !PICTURE_PNG.equalsIgnoreCase(type) && !PICTURE_JPG.equalsIgnoreCase(type) && !PICTURE_JPEG.equalsIgnoreCase(type)) {
            return ResponseUtil.badArgument();
        }
        String fileName = "license_" + id + "_" + randomName + "." + type;
        try {
            File saveFile = saveFile(file, fileName, request);
            JSONObject object = getLicenseInfo(saveFile);
            object.put("licenseFile", fileName);
            return ResponseUtil.ok(object);
        } catch (Exception e) {
            delFile(fileName);
            e.printStackTrace();
            if (e.getMessage().contains("OCR识别失败")) {
                return ResponseUtil.fail(500, "OCR识别失败");
            }
            return ResponseUtil.fail(500, e.getMessage());
        }
    }

    /**
     *  校验
     * @param license  证书内容
     * @param request  请求
     * @return
     */
    @PostMapping("verify")
    public Object verify(@RequestBody LitemallCustomerLicense license, HttpServletRequest request) {
        XxlSsoUser user = (XxlSsoUser) request.getAttribute(Conf.SSO_USER);
        Long id = Long.parseLong(user.getUserid());
        license.setCustomerId(id);
        String realPath = System.getProperty("user.dir");
        String path = realPath + "/license/" + license.getLicenseFile();
        File file = new File(path);
        if (!file.exists()) {
            return ResponseUtil.badArgument();
        }
        LitemallCustomer customer = customerService.getUser(id);
        if (customer.getUserState() != null && customer.getUserState() == 2) {
            return ResponseUtil.fail(403, "您已经进行过认证");
        }
        licenseService.insert(license);
        customer.setUserState(2);
        customerService.update(customer);
        return ResponseUtil.ok();
    }

    private File saveFile(MultipartFile file, String name, HttpServletRequest request) throws Exception {
        request.setCharacterEncoding("utf-8");
        if (file != null) {
            String realPath = System.getProperty("user.dir");
            String path = realPath + "/license/" + name;
            File dir = new File(realPath + "/license");
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File savedFile = new File(path);
            file.transferTo(savedFile);
            /**
             * 被复制到此文件中 如果文件上传出错.用底层 (spring3之后底层方法改了,容易报错)
             *   // FileOutputStream os=new FileOutputStream(savedFile);
             *   // FileCopyUtils.copy(file.getInputStream(),os);
             */

            ImageUtil.compressImage(path);
            return savedFile;
        }
        throw new Exception("get no file!!!");
    }

    /**
     *  删除证书
     * @param name 证书上传后的 唯一名
     * @return
     */
    private boolean delFile(String name) {
        String realPath = System.getProperty("user.dir");
        String path = realPath + "/license/" + name;
        File savedFile = new File(path);
        return savedFile.delete();
    }

    /**
     *
     * @param body
     * @param request  携带信息Authorization:74_18d1e63065d943c6b019e619be9abd6c
     * @return
     */
    @PostMapping("update")
    public Object update(@RequestBody String body, HttpServletRequest request) {
        XxlSsoUser user = (XxlSsoUser)  request.getAttribute(Conf.SSO_USER);
        Long id = Long.parseLong(user.getUserid());
        LitemallCustomer customerIn = JSONObject.parseObject(body, LitemallCustomer.class);
        /**
         * 昵称 验证 : 1非空不能超过10个字符  2屏蔽不当词汇
         */
        String nickName = customerIn.getNickname();
        if(StringUtils.isNotEmpty(nickName) )if(nickName.length() > 10){
            return ResponseUtil.fail(402, "昵称不能超过10位");
        }
        if (StringUtils.isNotEmpty(nickName)) if (BadWordUtil.isContaintBadWord(nickName, BadWordUtil.maxMatchType)) {
            return ResponseUtil.fail(403, "您的昵称中有不和谐词汇");
        }
        /**
         * 数据库username 长度最高限制为 50 ..这里限制10..以前如果走更新接口会 炸数据库
         */
        String userName =  customerIn.getUsername();
        if(StringUtils.isNotEmpty(userName) && userName.length() > 15){    return ResponseUtil.fail(402, "姓名不能超过15位");}
        String gender = customerIn.getGender();
        String phone = customerIn.getPhone();
        String avatar = customerIn.getAvatar();
        /**
         * 邮箱 1不为空. 2验证邮箱 3邮箱数据库设计师50位..超过会报错..此处做限制
         */
        String mail = customerIn.getMail();
        if ( !StringUtils.isEmpty(mail) ) {
            if(!RegexUtil.isEmail(mail)){
                return ResponseUtil.fail(402, "您填写的邮箱格式不正确");
            }
            if(mail.length()>50){
                return ResponseUtil.fail(402, "邮箱不能超过50位");
            }
        }

        /**
         * 如果邮箱为空  设置为null???
         */
        if (StringUtils.isEmpty(mail)) {
            mail = null;
        }
        String userPassword = customerIn.getUserPassword();

        /**
         * 手机号码 验证  :手机号码与验证码
         */
        LitemallCustomer customer = customerService.getUser(id);
        String oldPhone = customer.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            String checkCode = JacksonUtil.parseString(body, "checkCode");
            String captcha = JacksonUtil.parseString(body, "captcha");
            if (StringUtils.isAnyEmpty(checkCode, captcha)) {
                return ResponseUtil.fail(402, "您填写的验证码不正确");
            }
            String trueCode = CaptchaCodeManager.getCachedCaptcha(oldPhone);
            String trueCaptcha = CaptchaCodeManager.getCachedCaptcha(phone);
            if (!checkCode.equals(trueCode) || !captcha.equals(trueCaptcha)) {
                return ResponseUtil.fail(402, "您填写的验证码不正确");
            }
            CaptchaCodeManager.setNullCode(phone, oldPhone);
        }


        if (StringUtils.isNotEmpty(userPassword)) {
            if (!RegexUtil.isPassword(userPassword)) {
                return ResponseUtil.fail(402, "您填写的密码过于简单");
            }
            String oldPassword = JacksonUtil.parseString(body, "oldPassword");
            if (StringUtils.isEmpty(oldPassword)) {
                String captcha = JacksonUtil.parseString(body, "captcha");
                if (StringUtils.isEmpty(captcha)) {
                    return ResponseUtil.fail(402, "请输入校验");
                }
                if (upCaptchaCheck(id, captcha)) {
                    userPassword = MD5Util.md5(userPassword, "frost_forest");
                }
                else {
                    return ResponseUtil.fail(402, "您填写的旧密码不正确");
                }
            }
            else {
                oldPassword = MD5Util.md5(oldPassword, "frost_forest");
                LitemallCustomer customerOld = customerService.getUser(id, oldPassword);
                if (customerOld == null) {
                    return ResponseUtil.fail(402, "您填写的旧密码不正确");
                }
                userPassword = MD5Util.md5(userPassword, "frost_forest");
            }
        }
        try {
            /**
             * 昵称 验证 : 1非空不能超过10个字符  2屏蔽不当词汇
             */
            //05.01 BUG 前端刷新后..之前拦截不住...昵称.重新拦截验证
            if(StringUtils.isNotEmpty(nickName) )if(nickName.length() > 10){
                return ResponseUtil.fail(402, "昵称不能超过10位");
            }
            if (StringUtils.isNotEmpty(nickName)) if (BadWordUtil.isContaintBadWord(nickName, BadWordUtil.maxMatchType)) {
                return ResponseUtil.fail(403, "您的昵称中有不和谐词汇");
            }
            LitemallCustomer newCustomer = new LitemallCustomer(nickName, userName, gender, phone, mail, userPassword, avatar);
            newCustomer.setId(id);
            customerService.update(newCustomer);
            return ResponseUtil.ok();
        } catch (DuplicateKeyException e) {
            String errMsg = "重复";
            if (e.toString().contains("mail_uindex")) {
                errMsg = "邮箱" + errMsg;
            }
            if (e.toString().contains("phone_uindex")) {
                errMsg = "手机" + errMsg;
            }
            return ResponseUtil.fail(401,errMsg);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.fail(500, "数据格式不正确");
        }
    }
}
